package com.gzc.just.play.last.war.centralserver.matchmaking;

import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 战斗匹配器 - 负责匹配玩家进行战斗
 * 
 * @author AI编程助手
 * @version 1.0
 */
public class BattleMatchmaker {
    
    /**
     * 匹配结果
     */
    public static class MatchResult {
        public MatchmakingRequest player1;
        public MatchmakingRequest player2;
        public long matchTime;
        
        public MatchResult(MatchmakingRequest player1, MatchmakingRequest player2) {
            this.player1 = player1;
            this.player2 = player2;
            this.matchTime = System.currentTimeMillis();
        }
    }
    
    private final List<MatchmakingRequest> waitingQueue = new CopyOnWriteArrayList<>();
    private final List<MatchResult> matchResults = new CopyOnWriteArrayList<>();
    private final List<MatchmakerListener> listeners = new CopyOnWriteArrayList<>();
    private static final int BATCH_SIZE = 100; // 每次匹配最多处理100个请求
    
    /**
     * 添加匹配请求
     * 
     * @param request 匹配请求
     * @return 是否成功添加
     */
    public boolean addRequest(MatchmakingRequest request) {
        if (request == null) {
            return false;
        }
        
        // 检查是否已在队列中
        for (MatchmakingRequest r : waitingQueue) {
            if (r.getPlayerId() == request.getPlayerId()) {
                return false;
            }
        }
        
        return waitingQueue.add(request);
    }
    
    /**
     * 移除匹配请求
     * 
     * @param playerId 玩家ID
     * @return 是否成功移除
     */
    public boolean removeRequest(long playerId) {
        for (MatchmakingRequest request : waitingQueue) {
            if (request.getPlayerId() == playerId) {
                request.cancel();
                return waitingQueue.remove(request);
            }
        }
        return false;
    }
    
    /**
     * 获取玩家的匹配请求
     * 
     * @param playerId 玩家ID
     * @return 匹配请求
     */
    public MatchmakingRequest getRequest(long playerId) {
        for (MatchmakingRequest request : waitingQueue) {
            if (request.getPlayerId() == playerId) {
                return request;
            }
        }
        return null;
    }
    
    /**
     * 执行一次匹配操作
     * 
     * @return 匹配成功的结果列表
     */
    public List<MatchResult> performMatching() {
        List<MatchResult> results = new ArrayList<>();
        
        // 清理过期请求
        cleanupExpiredRequests();
        
        // 按等级排序
        List<MatchmakingRequest> sorted = sortByLevel();
        
        // 进行匹配
        Set<Long> matched = new HashSet<>();
        int processCount = Math.min(sorted.size(), BATCH_SIZE);
        
        for (int i = 0; i < processCount; i++) {
            MatchmakingRequest request1 = sorted.get(i);
            
            if (matched.contains(request1.getPlayerId())) {
                continue;
            }
            
            // 寻找合适的对手
            for (int j = i + 1; j < sorted.size(); j++) {
                MatchmakingRequest request2 = sorted.get(j);
                
                if (matched.contains(request2.getPlayerId())) {
                    continue;
                }
                
                if (request1.canMatchWith(request2)) {
                    // 匹配成功
                    request1.markMatched();
                    request2.markMatched();
                    
                    matched.add(request1.getPlayerId());
                    matched.add(request2.getPlayerId());
                    
                    MatchResult result = new MatchResult(request1, request2);
                    results.add(result);
                    matchResults.add(result);
                    
                    notifyMatched(result);
                    break;
                }
            }
        }
        
        return results;
    }
    
    /**
     * 清理过期的匹配请求
     */
    private void cleanupExpiredRequests() {
        List<MatchmakingRequest> toRemove = new ArrayList<>();
        
        for (MatchmakingRequest request : waitingQueue) {
            if (request.isExpired()) {
                toRemove.add(request);
                notifyRequestExpired(request);
            }
        }
        
        waitingQueue.removeAll(toRemove);
    }
    
    /**
     * 按等级排序
     * 
     * @return 排序后的请求列表
     */
    private List<MatchmakingRequest> sortByLevel() {
        List<MatchmakingRequest> sorted = new ArrayList<>(waitingQueue);
        sorted.sort((a, b) -> {
            // 按评分从高到低排序
            int ratingCompare = Integer.compare(b.getRating(), a.getRating());
            if (ratingCompare != 0) {
                return ratingCompare;
            }
            // 评分相同，按等级排序
            return Integer.compare(b.getPlayerLevel(), a.getPlayerLevel());
        });
        return sorted;
    }
    
    /**
     * 获取等待队列大小
     * 
     * @return 队列中的请求数
     */
    public int getQueueSize() {
        return waitingQueue.size();
    }
    
    /**
     * 获取总匹配数
     * 
     * @return 匹配总数
     */
    public int getTotalMatches() {
        return matchResults.size();
    }
    
    /**
     * 获取平均等待时间（毫秒）
     * 
     * @return 平均等待时间
     */
    public long getAverageWaitingTime() {
        if (waitingQueue.isEmpty()) {
            return 0;
        }
        
        long totalWait = 0;
        for (MatchmakingRequest request : waitingQueue) {
            totalWait += request.getWaitingTime();
        }
        
        return totalWait / waitingQueue.size();
    }
    
    /**
     * 添加监听器
     * 
     * @param listener 监听器
     */
    public void addListener(MatchmakerListener listener) {
        if (listener != null) {
            listeners.add(listener);
        }
    }
    
    /**
     * 移除监听器
     * 
     * @param listener 监听器
     */
    public void removeListener(MatchmakerListener listener) {
        listeners.remove(listener);
    }
    
    private void notifyMatched(MatchResult result) {
        for (MatchmakerListener listener : listeners) {
            listener.onMatched(result);
        }
    }
    
    private void notifyRequestExpired(MatchmakingRequest request) {
        for (MatchmakerListener listener : listeners) {
            listener.onRequestExpired(request);
        }
    }
    
    /**
     * 匹配器监听器接口
     */
    public interface MatchmakerListener {
        void onMatched(MatchResult result);
        void onRequestExpired(MatchmakingRequest request);
    }
}
